package org.geektimes.projects.user.web.controller;

import org.apache.commons.lang.StringUtils;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.web.mvc.controller.PageController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.ws.rs.Path;
import java.util.Set;

/**
 * @author guozhan
 * @description TODO
 * @date 2021/3/8 17:40
 */
@Path("/register")
public class RegisterController implements PageController {

    @Resource(name = "bean/UserService")
    private UserService userService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        if(request.getParameterMap().isEmpty()) {
            return "register.jsp";
        }

        User user =  assembleUser(request);

        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

        Validator validator = validatorFactory.getValidator();

        Set<ConstraintViolation<User>> validate = validator.validate(user);
        if(validate.size() > 0) {
            validate.forEach(err -> System.out.println(err.getMessage()));
            return "validation-failed.jsp";
        }
        if(userService.queryByUsername(user.getName()) == null) {
            userService.register(user);
            return "register-success.jsp";
        }else {
            return "user-existed.jsp";
        }


    }

    private User assembleUser(HttpServletRequest request) {
        User user = new User();
//        user.setId((long)Math.random());
        if(!StringUtils.isEmpty(request.getParameter("username"))){
            user.setName(request.getParameter("username"));
        }

        if(!StringUtils.isEmpty(request.getParameter("password"))){
            user.setPassword(request.getParameter("password"));
        }

        if(!StringUtils.isEmpty(request.getParameter("email"))){
            user.setEmail(request.getParameter("email"));
        }

        if(!StringUtils.isEmpty(request.getParameter("phoneNumber"))){
            user.setPhoneNumber(request.getParameter("phoneNumber"));
        }

        return user;
    }
}
